﻿@using ApiLib.RCL.Models
@using ApiLib.RCL.Utils
@inject DownloadService DownloadService
@inject MessageService MessageService

<div class="row" style="max-width: 400px;">
    @foreach (var file in Files)
    {
        <div class="col-auto row" style="cursor: pointer" @onclick="@(async _ => await Download(file))">
            @*<Tooltip Placement="Placement.Auto" Title="@file.Name">
            </Tooltip>*@
            @if (file.IsImage())
            {
                <ImageViewer Url="@file.Path" FitMode="ObjectFitMode.Contain" PreviewList="_previewList"/>
            }
            else
            {
                <FileIcon class="custom-icon" Extension="@file.Ext" IconColor="Color.Primary"/>
            }
        </div>
    }
</div>
@* <ImagePreview @ref="_imagePreviewer"></ImagePreview> *@

@code {

    [Parameter] public string FilePaths { get; set; }
    [Parameter] public List<FileInfo> Files { get; set; } = new();

    private string _host => WebApp.Host;
    private ImagePreview _imagePreviewer;
    private List<string> _previewList = new();

    protected override async Task OnInitializedAsync()
    {
        if (!string.IsNullOrEmpty(FilePaths))
        {
            Files.AddRange(FilePaths.Split(",")
                .Where(str => !string.IsNullOrEmpty(str))
                .Select(str => new FileInfo(Path.Combine(_host, str)))
                .ToList());
            if (Files.Count > 0)
            {
                _previewList.AddRange(Files.Select(info => info.Path).ToList());
            }
        }
    }

    private async Task Download(FileInfo file)
    {
        if (file.IsImage())
        {
            // _imagePreviewer.Show(file.Path);
            return;
        }
        // await DownloadService.DownloadFromUrlAsync(file.Name, file.Path);
        var stream = await HttpUtil.DownloadAsync(file.Path);
        if (stream!=null)
        {
            await DownloadService.DownloadFromStreamAsync(file.Name, stream);
        }
        else
        {
            await MessageService.MessageWarning("下载失败");
        }
    }

}